package cn.lingyangwl.agile.misc.short_link.mapper;

import cn.lingyangwl.agile.misc.short_link.config.*;
import cn.lingyangwl.agile.misc.short_link.model.entity.*;
import cn.lingyangwl.agile.misc.short_link.utils.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Component;

/**
 * @author shenguangyang
 */
@Component
public class SlShortLinkManager extends ServiceImpl<SlShortLinkMapper, ShortLink> {

    public String createShortLinkCode(String str) {
        long murMurHash = ShortLinkUtils.createStringCode(str);
        String code = this.encodeToBase64(murMurHash);
        return ShardingDBConfig.getRandomPrefix(code) + code + ShardingTableConfig.getRandomSuffix(code);
    }

    /**
     * 将数字转为62进制。小端，个位数在前。
     */
    public String encodeToBase64(long number) {
        final char[] NumberToText_SIXTWO_ARR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
        final int scale = 62;
        StringBuilder sb = new StringBuilder(12);
        boolean negative = number < 0;
        if (negative) number = -number;
        if (number < 0) return "8m85Y0n8LzA-";
        //SU.Log("NumberToText_SIXTWO_LE", number, -(number+1));
        long remainder;
        while (number != 0) {
            remainder = number % scale;
            sb.append(NumberToText_SIXTWO_ARR[(int) remainder]);
            number = number / scale;
        }
        if (negative) sb.append('-');
        return sb.toString();
    }

    /**
     * 62进制字符串转为数字。小端，个位数在前。
     */
    public long decodeBase64(String text) {
        if ("8m85Y0n8LzA-".equals(text)) return Long.MIN_VALUE;
        final int scale = 62;
        long num = 0;
        int len = text.length(), i = len - 1;
        if (len > 0) {
            boolean negative = text.charAt(0) == '-';
            if (negative) i--;
            int index;
            char c;
            for (; i >= 0; i--) {
                c = text.charAt(i);
                if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
                    if (c >= 'a') {
                        index = c - 'a' + 36;
                    } else {
                        index = c - 'A' + 10;
                    }
                } else {
                    index = (c - '0') % 10;
                }
                num += (long) (index * (Math.pow(scale, i)));
            }
            if (negative) num = -num;
        }
        return num;
    }
}
